package com.example.myapplication.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.data.model.BreadcrumbItem
import com.example.myapplication.data.model.StorageItem
import com.example.myapplication.data.model.StorageSpace
import com.example.myapplication.data.repository.StorageItemRepository
import com.example.myapplication.data.repository.StorageSpaceRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import java.util.UUID
import javax.inject.Inject

/**
 * 储物空间详情UI状态
 */
data class StorageDetailUiState(
    val isLoading: Boolean = false,
    val currentSpace: StorageSpace? = null,
    val childSpaces: List<StorageSpace> = emptyList(),
    val items: List<StorageItem> = emptyList(),
    val breadcrumbs: List<BreadcrumbItem> = emptyList(),
    val errorMessage: String? = null,
    val successMessage: String? = null, // 新增：成功消息
    val itemToDelete: StorageItem? = null, // State for deletion confirmation
    val itemToEdit: StorageItem? = null, // State for editing
    val itemToMove: StorageItem? = null,
    val allSpaces: List<StorageSpace> = emptyList(),
    // 新增：空间删除确认状态
    val spaceToDelete: StorageSpace? = null,
    val deleteConfirmationInfo: String? = null // 删除确认信息
)

/**
 * 储物空间详情ViewModel
 */
@HiltViewModel
class StorageDetailViewModel @Inject constructor(
    private val storageSpaceRepository: StorageSpaceRepository,
    private val storageItemRepository: StorageItemRepository
) : ViewModel() {

    private val _uiState = MutableStateFlow(StorageDetailUiState())
    val uiState: StateFlow<StorageDetailUiState> = _uiState.asStateFlow()

    private var currentSpaceId: String? = null

    /**
     * 加载储物空间详情
     */
    fun loadStorageDetail(spaceId: String) {
        if (currentSpaceId == spaceId && !_uiState.value.isLoading) return
        currentSpaceId = spaceId
        
        viewModelScope.launch {
            _uiState.update { it.copy(isLoading = true, errorMessage = null) }
            
            try {
                storageSpaceRepository.getSpaceByIdFlow(spaceId).collect { currentSpace ->
                    if (currentSpace == null) {
                        _uiState.update { it.copy(isLoading = false, errorMessage = "储物空间不存在") }
                        return@collect
                    }

                    val spacePath = storageSpaceRepository.getSpacePath(spaceId)
                    val breadcrumbs = generateBreadcrumbs(spacePath)

                    combine(
                        storageSpaceRepository.getChildSpaces(spaceId),
                        storageItemRepository.getItemsBySpaceId(spaceId)
                    ) { childSpaces, items ->
                        _uiState.update {
                            it.copy(
                                isLoading = false,
                                currentSpace = currentSpace,
                                childSpaces = childSpaces,
                                items = items,
                                breadcrumbs = breadcrumbs,
                                errorMessage = null
                            )
                        }
                    }.collect()
                }
            } catch (e: Exception) {
                _uiState.update { it.copy(isLoading = false, errorMessage = "加载储物空间详情失败: ${e.message}") }
            }
        }
    }

    /**
     * 添加子储物空间
     */
    fun addChildSpace(name: String, description: String?, iconType: String?) {
        currentSpaceId?.let { parentId ->
            viewModelScope.launch {
                try {
                    val newSpace = StorageSpace(
                        name = name,
                        description = description,
                        parentId = parentId,
                        iconType = iconType
                    )
                    storageSpaceRepository.insertOrUpdateSpace(newSpace)
                } catch (e: Exception) {
                    _uiState.update { it.copy(errorMessage = "添加子空间失败: ${e.message}") }
                }
            }
        }
    }

    /**
     * 添加物品
     */
    fun addItem(name: String, description: String?, quantity: Int, imagePath: String?) {
        currentSpaceId?.let { spaceId ->
            viewModelScope.launch {
                val newItem = StorageItem(
                    name = name,
                    description = description,
                    quantity = quantity,
                    imagePath = imagePath,
                    spaceId = spaceId
                )
                storageItemRepository.insertOrUpdateItem(newItem)
            }
        }
    }

    // --- Deletion Logic ---
    fun onDeleteItemInitiated(item: StorageItem) {
        _uiState.update { it.copy(itemToDelete = item) }
    }

    fun onDeleteItemCancelled() {
        _uiState.update { it.copy(itemToDelete = null) }
    }

    fun onDeleteItemConfirmed() {
        _uiState.value.itemToDelete?.let { item ->
            viewModelScope.launch {
                try {
                    storageItemRepository.deleteItemById(item.id)
                    _uiState.update { it.copy(itemToDelete = null, errorMessage = "物品 '${item.name}' 已删除") } // Show success message
                } catch (e: Exception) {
                    _uiState.update { it.copy(itemToDelete = null, errorMessage = "删除物品失败: ${e.message}") }
                }
            }
        }
    }
    // --- End Deletion Logic ---

    // --- Editing Logic ---
    fun onEditItemInitiated(item: StorageItem) {
        _uiState.update { it.copy(itemToEdit = item) }
    }

    fun onEditItemCancelled() {
        _uiState.update { it.copy(itemToEdit = null) }
    }

    fun onEditItemConfirmed(name: String, description: String?, quantity: Int, imagePath: String?) {
        _uiState.value.itemToEdit?.let { originalItem ->
            viewModelScope.launch {
                try {
                    val updatedItem = originalItem.copy(
                        name = name,
                        description = description,
                        quantity = quantity,
                        imagePath = imagePath,
                        updatedAt = System.currentTimeMillis()
                    )
                    storageItemRepository.insertOrUpdateItem(updatedItem)
                    _uiState.update { it.copy(itemToEdit = null, errorMessage = "物品 '${updatedItem.name}' 已更新") }
                } catch (e: Exception) {
                    _uiState.update { it.copy(itemToEdit = null, errorMessage = "更新物品失败: ${e.message}") }
                }
            }
        }
    }
    // --- End Editing Logic ---

    /**
     * 生成面包屑导航
     */
    private fun generateBreadcrumbs(spacePath: List<StorageSpace>): List<BreadcrumbItem> {
        val breadcrumbs = mutableListOf<BreadcrumbItem>()
        breadcrumbs.add(BreadcrumbItem(id = "root", name = "主页"))
        spacePath.forEachIndexed { index, space ->
            breadcrumbs.add(
                BreadcrumbItem(
                    id = space.id,
                    name = space.name,
                    isLast = index == spacePath.size - 1
                )
            )
        }
        return breadcrumbs
    }

    fun navigateToSpace(spaceId: String) {
        loadStorageDetail(spaceId)
    }

    fun deleteSpace(space: StorageSpace) {
        println("DEBUG: 尝试删除空间: ${space.name}")
        viewModelScope.launch {
            try {
                // 检查空间内容
                val hasChildren = storageSpaceRepository.hasChildSpaces(space.id)
                val itemCount = storageSpaceRepository.getItemCount(space.id)
                
                if (hasChildren || itemCount > 0) {
                    // 有内容时显示确认对话框
                    val confirmationInfo = buildString {
                        append("删除空间 '${space.name}' 将同时删除：\n")
                        if (hasChildren) append("• 所有子空间\n")
                        if (itemCount > 0) append("• ${itemCount}个物品\n")
                        append("\n此操作无法撤销，确定要继续吗？")
                    }
                    _uiState.update { 
                        it.copy(
                            spaceToDelete = space,
                            deleteConfirmationInfo = confirmationInfo
                        ) 
                    }
                    println("DEBUG: 显示删除确认对话框")
                } else {
                    // 空间为空，直接删除
                    performSpaceDeletion(space)
                }
            } catch (e: Exception) {
                _uiState.update { it.copy(errorMessage = "检查空间状态失败: ${e.message}") }
                println("DEBUG: 检查失败: ${e.message}")
            }
        }
    }

    /**
     * 执行空间删除
     */
    private suspend fun performSpaceDeletion(space: StorageSpace) {
        try {
            storageSpaceRepository.deleteSpace(space)
            _uiState.update { it.copy(successMessage = "空间 '${space.name}' 已删除") }
            println("DEBUG: 删除成功")
        } catch (e: Exception) {
            _uiState.update { it.copy(errorMessage = "删除空间失败: ${e.message}") }
            println("DEBUG: 删除失败: ${e.message}")
        }
    }

    /**
     * 确认删除空间
     */
    fun confirmSpaceDeletion() {
        val spaceToDelete = _uiState.value.spaceToDelete
        if (spaceToDelete != null) {
            viewModelScope.launch {
                performSpaceDeletion(spaceToDelete)
                _uiState.update { 
                    it.copy(
                        spaceToDelete = null,
                        deleteConfirmationInfo = null
                    ) 
                }
            }
        }
    }

    /**
     * 取消删除空间
     */
    fun cancelSpaceDeletion() {
        _uiState.update { 
            it.copy(
                spaceToDelete = null,
                deleteConfirmationInfo = null
            ) 
        }
    }

    fun updateSpace(spaceId: String, name: String, description: String?, iconType: String?) {
        viewModelScope.launch {
            try {
                val space = storageSpaceRepository.getSpaceById(spaceId)
                if (space != null) {
                    val updatedSpace = space.copy(
                        name = name,
                        description = description,
                        iconType = iconType
                    )
                    storageSpaceRepository.insertOrUpdateSpace(updatedSpace)
                    _uiState.update { it.copy(successMessage = "空间 '${name}' 更新成功") }
                }
            } catch (e: Exception) {
                _uiState.update { it.copy(errorMessage = "更新空间失败: ${e.message}") }
            }
        }
    }

    /**
     * 清除错误消息
     */
    fun clearErrorMessage() {
        _uiState.update { it.copy(errorMessage = null) }
    }

    /**
     * 清除成功消息
     */
    fun clearSuccessMessage() {
        _uiState.update { it.copy(successMessage = null) }
    }

    fun onMoveItemInitiated(item: StorageItem) {
        viewModelScope.launch {
            val allSpaces = storageSpaceRepository.getAllSpaces().first()
            _uiState.update { it.copy(itemToMove = item, allSpaces = allSpaces) }
        }
    }

    fun onMoveItemCancelled() {
        _uiState.update { it.copy(itemToMove = null, allSpaces = emptyList()) }
    }

    fun onMoveItemConfirmed(newSpaceId: String) {
        _uiState.value.itemToMove?.let { item ->
            viewModelScope.launch {
                try {
                    val updatedItem = item.copy(spaceId = newSpaceId)
                    storageItemRepository.insertOrUpdateItem(updatedItem)
                    _uiState.update { it.copy(itemToMove = null, allSpaces = emptyList(), errorMessage = "物品已移动") }
                } catch (e: Exception) {
                    _uiState.update { it.copy(itemToMove = null, allSpaces = emptyList(), errorMessage = "移动物品失败: ${e.message}") }
                }
            }
        }
    }
}